package io.mft.as.adapter;

import java.util.List;
import java.util.Map;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import io.mft.api.domain.Api;
import io.mft.as.adapter.bean.DBPage;
import io.mft.as.adapter.bean.DataRow;
import io.mft.as.adapter.bean.ResultVo;
import io.mft.as.adapter.exception.InvokeException;
import io.mft.as.ar.gateway.client.Client;
import io.mft.as.ar.gateway.config.BusConfig;
import io.mft.as.ar.gateway.config.BusIdConfig;
import io.mft.as.ar.gateway.config.bean.ARConfig;
import io.mft.as.ar.gateway.config.bean.ARServiceConfig;
import io.mft.as.ar.gateway.result.Result;
import io.mft.commons.exception.MFTException;
import io.mft.commons.function.RequestValue;
import io.mft.commons.function.response.DsName;
import io.mft.commons.function.response.kv.KVMap;
import io.mft.commons.function.response.kv.KVMapList;
import io.mft.commons.function.response.kv.PageObject;
import io.mft.dev.bootstrap.adapter.MFTRuningAdapter;
import io.mft.runtime.MFTApiExecutor;
import io.mft.runtime.function.ApiFunctionRequest;
import io.mft.runtime.function.ApiFunctionResponse;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MFTAsApiRuningAdapter extends MFTRuningAdapter<ResultVo> {

	@Override
	public void registerApi(Api api) {
		// TODO Auto-generated method stub
		
	}
	private boolean isJob(ApiFunctionRequest request) {
		String funcNo=request.getString("funcNo", "-1");
		String timestamp=request.getString("timestamp", "-1");
		String systemKey=request.getString("systemKey", "-1");
		String jobKey=request.getString("jobKey", "-1");
		String arConfig=request.getString("arConfig", "-1");
		String arServiceConfig=request.getString("arServiceConfig", "-1");
		String logid=request.getString("logid", "-1");
		String pollAsk=request.getString("pollAsk", "-1");
		if ("1".equals(pollAsk)) {
			return true;
		}
		if (verify(arServiceConfig)&&verify(arConfig)&&verify(jobKey)&&verify(systemKey)&&verify(timestamp)&&verify(funcNo)&&verify(logid)) {
			return true;
		}else {
			return false;
		}
	}
	
	public boolean verify(String v) {
		return "-1".equals(v)?false:true;
	}
	private ResultVo processJob(String funcNo,ApiFunctionRequest request){
		ResultVo resultVo=new ResultVo();
		String pollAsk=request.getRequestValue().getStr("pollAsk");//轮询检查
		if ("1".equals(pollAsk)) {
			log.info("功能号:{}->>>当前是JOB调度轮询请求,参数:{}",funcNo,request.getRequestValue());
			return resultVo;
		}
		try {
			log.info("功能号:{}->>>当前JOB调度请求执行开始,参数:{}",funcNo,request.getRequestValue());
			String arConfig=request.getRequestValue().getStr("arConfig");//时间戳
			String arServiceConfig=request.getRequestValue().getStr("arServiceConfig");//时间戳
			ARConfig arConfigObject=JSONUtil.parseObj(arConfig).toBean(ARConfig.class);
			ARServiceConfig arServiceConfigObject=JSONUtil.parseObj(arServiceConfig).toBean(ARServiceConfig.class);
			BusConfig.addConfig(arConfigObject);
			BusIdConfig.addConfig(arServiceConfigObject);
			ApiFunctionResponse response=MFTApiExecutor.getInstance().execute(funcNo,request);
			resultVo.setErrorMsg(response.getErrorInfo());
			resultVo.setErrorNo(response.getErrorNo());
			log.info("功能号:{}->>>当前JOB调度请求执行完成,参数:{}",funcNo,request.getRequestValue());
			return resultVo;
		} catch (Throwable e) {
			log.error("",e);
			resultVo.setErrorNo(-1);
			resultVo.setErrorMsg("系统处理异常:"+e.getMessage());
			return resultVo;
		}finally {
			try {
				DataRow parameter = new DataRow();
				parameter.set("logid", request.getRequestValue().getStr("logid"));
				parameter.set("jobKey", request.getRequestValue().getStr("jobKey"));
				parameter.set("jobName", request.getRequestValue().getStr("jobName"));
				parameter.set("systemKey", request.getRequestValue().getStr("systemKey"));
				parameter.set("systemName", request.getRequestValue().getStr("systemName"));
				parameter.set("funcNo", request.getRequestValue().getStr("funcNo"));
				parameter.set("error_no", resultVo.getErrorNo());
				parameter.set("timestamp", request.getRequestValue().getStr("timestamp"));
				if (ObjectUtil.isEmpty(resultVo.getErrorMsg())) {
					if (resultVo.getErrorNo()==0) {
						parameter.set("error_info", "Success");
					}else {
						parameter.set("error_info","Fail");
					}
					
				}else {
					parameter.set("error_info", resultVo.getErrorMsg());
				}
				log.info("开始-调用集中调度回调接口:{}",parameter);
				Client client = new Client("jobExecutor");
				Result result=client.invokeToResult(2080002, parameter);
				log.info("结束-调用集中调度回调接口:{}-状态:[{}-{}]",parameter,result.getErr_no(),result.getErr_info());
			} catch (Exception e2) {
				log.error("", e2);
			}
		}
	}
	
	
	
	private ResultVo processApi(String funcNo,ApiFunctionRequest request){
		try {
			ApiFunctionResponse response=MFTApiExecutor.getInstance().execute(funcNo, request);
					//MFTApiRuntimeFunctionInvoker.invoke(funcNo,request);
			ResultVo resultVo = new ResultVo();
			if (response.getErrorNo() == 0) {
				List<io.mft.commons.function.response.DsName> dsSet = response.getDsName();
				for (DsName dsName : dsSet) {
					switch (dsName.getType()) {
					case list:
						KVMapList list = response.list(dsName.getName());
						resultVo.setResult(dsName.getAliasName(), list);
						break;
					case map:
						KVMap map = response.data(dsName.getName());
						resultVo.setResult(dsName.getAliasName(), map);
						break;
					case page:
						PageObject<KVMap> pageObject = response.pageObject();
						DBPage dbPage = new DBPage(pageObject.getCurrPage(), pageObject.getPageSize());
						dbPage.setTotalRows(pageObject.getTotalCount());
						dbPage.setData(pageObject.getList());
						resultVo.setResult(dsName.getAliasName(),dbPage);
						break;
					default:
						break;
					}
				}
			}
			resultVo.setErrorNo(response.getErrorNo());
			resultVo.setErrorMsg(response.getErrorInfo());
			return resultVo;
		} catch (InvokeException e) {
			throw e;
		}catch (MFTException e) {
			log.error("", e);
			throw new InvokeException("系统操作失败[原因:"+e.getMessage()+"],请稍后再试！",1);
		}catch (Exception e) {
			log.error("", e);
			throw new InvokeException("系统操作频繁,请稍后再试！", 1);
		}catch (Throwable e) {
			log.error("", e);
			throw new InvokeException("系统操作频繁,请稍后再试！", 1);
		}
	}
	
	@Override
	public ResultVo executeApi(String funcNo, Map<String, Object> parameter) {
		RequestValue requestValue = new RequestValue();
		requestValue.putAll(parameter);
		ApiFunctionRequest request = new ApiFunctionRequest(requestValue);
		boolean isJobRequest = isJob(request);
		if (isJobRequest) {
			return processJob(funcNo, request);
		} else {
			return processApi(funcNo, request);
		}
	}
	@Override
	public void unregisterApi(Api api) {
		// TODO Auto-generated method stub
		
	}

}
